package org.freemarker.web.controller;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.freemarker.core.model.Car;
import org.freemarker.core.service.CarService;
import org.freemarker.web.custom.CustomHttpServlet;
import org.springframework.beans.factory.annotation.Autowired;

public class FilteredCarListController extends CustomHttpServlet{
	private static final long serialVersionUID = 4447359168926713944L;
	
	@Autowired
	private CarService carService;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		List<Car> cars =carService.findAll();
		Set<String> brands = carService.getBrands();
		

		
		req.setAttribute("cars", cars);
		req.setAttribute("brands", brands);
		req.getRequestDispatcher("views/sandbox/filteredCarList.ftl").forward(req,res);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		List<Car> cars ;
		Set<String> brands = carService.getBrands();
		
		String brandFilter = req.getParameter("brand");
		if(brandFilter==null || brandFilter.length()==0){
			cars= carService.findAll();
		}else{//if a filter was selected, forward the filtered list
			cars= carService.getByBrand(brandFilter);
		}
		req.setAttribute("cars", cars);
		req.setAttribute("brands", brands);
		
		req.getRequestDispatcher("views/sandbox/filteredCarList.ftl").forward(req,res);
	}
}
